#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    cam(0)
{
    ui->setupUi(this);
    face = new Face;
    ui->image->setPixmap(QPixmap(":/user.png"));
    sound = new QSound(":/success.wav",this);
    ui->image->setScaledContents(true);
    timer = new QTimer(this);
    //timer作信号触发update
    connect(timer, &QTimer::timeout, this, &Widget::update);
    dataTimerId = startTimer(500);
    timer->start(40);
    db = new Database("stu.db");
}

void Widget::update(){
    //创建摄像头对象
    cv::Mat image;
    cam >> image;
    //设置flag防止重复识别，当按开始打卡后才开始检测识别人脸
    if(flag == 1){
        frame++;
        //timer每40ms触发一次update，触发5次则检测一次人脸，即每200ms检测一次人脸
        if((frame%5) == 0)
        {
            if(face->detect(image, range))
            {
                hit++;
                ui->label_remind->setText("识别中，请保持不动");
            }else{
                hit = 0;
            }
        }
        //连续5次检测到人脸后，进行人脸识别
        if(5 == hit){
            ui->label_remind->setText("识别成功");
            cv::Mat faceimg(image);
            if(face->recognize(faceimg, user)){
                std::string info("姓名：");
                std::string name;
                db->getname(user.id, name);
                info.append(name);
                info.append("\n");
                info.append("学号：");
                info.append(user.id.c_str());
                info.append("\n");
                info.append("匹配度：");
                info.append(user.score.c_str());
                info.append("\n");
                ui->label_info->setText(info.c_str());
                ui->label_time_now->setText(QDateTime::currentDateTime().toString("时间：hh:mm:ss"));
                db->punch(user.id,QDateTime::currentDateTime().toTime_t());
                std::string pix=":/"+user.id+".jpg";
                ui->image->setPixmap(QPixmap(pix.c_str()));
                ui->image->setScaledContents(true);
                sound->play();
            }
            hit = 0;
            flag = 0;
        }
    }

    //图像格式转换，在label上显示摄像头图像
    cv::rectangle(image, range, CV_RGB(255, 0, 0));
    cv::cvtColor(image, image, CV_BGR2RGB);
    QImage qimage(image.data, image.cols, image.rows, image.step, QImage::Format_RGB888);
    ui->label_cam->setPixmap(QPixmap::fromImage(qimage));
}

//显示当前时间
void Widget::timerEvent(QTimerEvent *event){
    if(event->timerId() == dataTimerId){
     QString str = QDateTime::currentDateTime().toString("日期:yyyy年MM月dd日\n时间:hh:mm:ss");
      ui->label_time->setText(str);
    }
}


void Widget::on_pushButton_clicked()
{
    flag = 1;
   timer->start(40);
}


Widget::~Widget()
{
    delete ui;
}


